home *** CD-ROM | disk | FTP | other *** search
/ EnigmA Amiga Run 1997 February / EnigmA AMIGA RUN 15 (1997)(G.R. Edizioni)(IT)[!][issue 1997-02][PLANET CD V].iso / enigma / earcd / emula / arosdv19.lha / AROS / clib / realloc.c < prev    next >
C/C++ Source or Header  |  1996-10-24  |  2KB  |  91 lines

  1. /*
  2.     (C) 1995-96 AROS - The Amiga Replacement OS
  3.     $Id: realloc.c,v 1.2 1996/10/23 14:13:41 aros Exp $
  4.  
  5.     Desc: ANSI C function realloc()
  6.     Lang: english
  7. */
  8. #include <aros/machine.h>
  9. #include <clib/exec_protos.h>
  10.  
  11. /*****************************************************************************
  12.  
  13.     NAME */
  14.     #include <sys/types.h>
  15.     #include <memory.h>
  16.  
  17.     void * realloc (
  18.  
  19. /*  SYNOPSIS */
  20.     void * oldmem,
  21.     size_t size)
  22.  
  23. /*  FUNCTION
  24.     Change the size of an allocated part of memory. The memory must
  25.     have been allocated by malloc() or calloc(). If you reduce the
  26.     size, the old contents will be lost. If you enlarge the size,
  27.     the new contents will be undefined.
  28.  
  29.     INPUTS
  30.     oldmen - What you got from malloc() or calloc().
  31.     size - The new size.
  32.  
  33.     RESULT
  34.     A pointer to the allocated memory or NULL. If you don't need the
  35.     memory anymore, you can pass this pointer to free(). If you don't,
  36.     the memory will be freed for you when the application exits.
  37.  
  38.     NOTES
  39.     If you get NULL, the memory at oldmem will not have been freed and
  40.     can still be used.
  41.  
  42.     EXAMPLE
  43.  
  44.     BUGS
  45.  
  46.     SEE ALSO
  47.     free(), malloc(), calloc()
  48.  
  49.     INTERNALS
  50.  
  51.     HISTORY
  52.     24-12-95    digulla created
  53.  
  54. ******************************************************************************/
  55. {
  56.     UBYTE * mem, * newmem;
  57.     size_t oldsize;
  58.  
  59.     if (!oldmem)
  60.     return malloc (size);
  61.  
  62.     mem = (UBYTE *)oldmem - AROS_ALIGN(sizeof(size_t));
  63.     oldsize = *((size_t *)mem);
  64.  
  65.     /* Reduce or enlarge the memory ? */
  66.     if (size < oldsize)
  67.     {
  68.     /* Don't change anything for small changes */
  69.     if ((oldsize - size) < 4096)
  70.         newmem = oldmem;
  71.     else
  72.         goto copy;
  73.     }
  74.     else if (size == oldsize) /* Keep the size ? */
  75.     newmem = oldmem;
  76.     else
  77.     {
  78. copy:
  79.     newmem = malloc (size);
  80.  
  81.     if (newmem)
  82.     {
  83.         CopyMem (oldmem, newmem, size);
  84.         free (oldmem);
  85.     }
  86.     }
  87.  
  88.     return newmem;
  89. } /* malloc */
  90.  
  91.